var api = require('../config/api.js');

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 封封微信的的request
 */
function request(url, data = {}, method = "GET") {
  return new Promise(function(resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
        'token': wx.getStorageSync('token'),
        'Cookie': 'JSESSIONID=' + wx.getStorageSync('sessionId')
      },
      success: function(res) {
        if (res.data.success) {
          resolve(res.data);
        } else {
          if (res.data.data) {
            wx.navigateTo({
              url: '/pages/register/register1/register1',
            })
          } else {
            resolve(res.data);
          }

        }

      },
      fail: function(err) {
        reject(err)
        console.log("failed")
      }
    })
  });
}

/**
 * 检查微信会话是否过期
 */
function checkSession() {
  return new Promise(function(resolve, reject) {
    wx.checkSession({
      success: function() {
        resolve(true);
      },
      fail: function() {
        reject(false);
      }
    })
  });
}



/**
 * 封封微信的的request
 */
function requestPost(url, data = {}, method = "POST") {
  return new Promise(function(resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'token': wx.getStorageSync('token'),
        'Cookie': 'JSESSIONID=' + wx.getStorageSync('sessionId')
      },
      success: function(res) {
        if (res.data.success) {
          resolve(res.data);
        } else {
          if (res.data.data) {
            wx.navigateTo({
              url: '/pages/register/register1/register1'
            })
          } else {
            resolve(res.data);
          }

        }

      },
      fail: function(err) {
        reject(err)
        console.log("failed")
      }
    })
  });
}



/**
 * 判断手机号
 * @param {Number} num
 */
function checkPhone(num) {
  return /^1(3|4|5|7|8)\d{9}$/.test(num)
}

function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    image: '/img/icon_error.png'
  })
}


function isLogin(url) {
  if (!wx.getStorageSync('token')) {
    wx.navigateTo({
      url: '/pages/register/register1/register1',
    })
  }else{
    wx.navigateTo({
      url: url,
    })
  }
}


function getUser() {
  return wx.getStorageSync('user');
}


/**
 * 支付
 */
function payOrder(orderId, payType, payMoney) {
  return new Promise(function(resolve, reject) {
    request(api.ToPayUrl, {
      orderId: orderId,
      payType: payType,
      payMoney: payMoney
    }).then((res) => {
      console.log(res)
      if (res.success) {
        const payParam = res.data;
        wx.requestPayment({
          'timeStamp': payParam.timeStamp,
          'nonceStr': payParam.nonceStr,
          'package': payParam.package,
          'signType': payParam.signType,
          'paySign': payParam.paySign,
          'success': function(res) {
            resolve(res);
          },
          'fail': function(res) {
            reject(res);
          },
          'complete': function(res) {
            reject(res);
          }
        });
      } else {
        resolve(res.data);
      }
    });
  });
}




function getBuyNum(price) {
  let typeEnum = {
    item: {
      value: '1949',
      num: '2'
    },
    boon: {
      value: '1899',
      num: '20'
    },
    group: {
      value: '1849',
      num: '50'
    },
    test1: {
      value: '0.03',
      num: '2'
    },
    test2: {
      value: '0.04',
      num: '20'
    },
    test3: {
      value: '0.05',
      num: '50'
    }
  };
  for (let key in typeEnum) {
    if (typeEnum[key].value != undefined && typeEnum[key].value == price) {
     return typeEnum[key].num;
    }
  }
  return '1'
}


module.exports = {
  formatTime,
  request,
  requestPost,
  showErrorToast,
  checkSession,
  checkPhone,
  isLogin,
  payOrder,
  getUser,
  getBuyNum
}